//
//  BDTixianViewController.m
//  iOS_beboy
//
//  Created by admin on 2017/11/9.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDTixianViewController.h"
#import "DNPayAlertView.h"
#import "BDUserModel.h"
#import "BDForgetPasswordViewController.h"

@interface BDTixianViewController ()<UITextFieldDelegate,UIAlertViewDelegate>{
    UIView *errorView;
    NSInteger errorCode;
}

@property (nonatomic, strong) UITextField *firstTextField;
@property (nonatomic, strong) UITextField *secondTextField;
@property (nonatomic, strong) UITextField *thirdTextField;
@property (nonatomic, strong) UIButton *sureButton;
@property (nonatomic, strong) NSMutableDictionary *paraDic;

@end

@implementation BDTixianViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = ASLocalizedString(@"提现");
    self.paraDic = [NSMutableDictionary dictionary];
    [self createUI];
}

-(void)createUI{
    UILabel *careLabel = [[UILabel alloc] init];
    careLabel.top = kBDTopHeight;
    careLabel.left = 0;
    careLabel.size = CGSizeMake(kBDScreenWidth, 30);
    careLabel.text = ASLocalizedString(@"目前只支持支付宝提现，其他暂时不支持，谢谢!");
    careLabel.font = [UIFont systemFontOfSize:12];
    careLabel.textColor = [UIColor colorWithHexString:@"ff992b"];
    careLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:careLabel];
    
    UIView *backView = [[UIView alloc] init];
    backView.top = careLabel.bottom;
    backView.left = 0;
    backView.size = CGSizeMake(kBDScreenWidth, 55 * 2);
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    
    UILabel *firstLabel = [[UILabel alloc] init];
    firstLabel.left = 0;
    firstLabel.top = 0;
    firstLabel.text = ASLocalizedString(@"支付宝真名：");
    firstLabel.font = [UIFont systemFontOfSize:15];
    firstLabel.textColor = [UIColor colorWithHexString:@"666666"];
    [firstLabel sizeToFit];
    
    
    self.firstTextField = [[UITextField alloc] init];
    _firstTextField.top = 0;
    _firstTextField.left = 15;
    _firstTextField.size = CGSizeMake(kBDScreenWidth, 55);
    _firstTextField.textColor = [UIColor colorWithHexString:@"333333"];
    _firstTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:ASLocalizedString(@"请输入支付宝真名")attributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"cdcdcd"],NSFontAttributeName:[UIFont systemFontOfSize:15]}];
    _firstTextField.leftViewMode = UITextFieldViewModeAlways;
    _firstTextField.leftView = firstLabel;
    _firstTextField.delegate = self;
    [backView addSubview:_firstTextField];
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPath];
    [bezierPath moveToPoint:CGPointMake(0, _firstTextField.bottom)];
    [bezierPath addLineToPoint:CGPointMake(kBDScreenWidth, _firstTextField.bottom)];
    
    CAShapeLayer *pointerLayer = [CAShapeLayer layer];
    [pointerLayer setLineWidth:1];
    [pointerLayer setStrokeColor:[UIColor colorWithHexString:@"cccccc"].CGColor];
    pointerLayer.path = bezierPath.CGPath;
    
    [backView.layer addSublayer:pointerLayer];
    
    
    UILabel *secondLabel = [[UILabel alloc] init];
    secondLabel.left = 0;
    secondLabel.top = 0;
    secondLabel.text = ASLocalizedString(@"支付宝账号：");
    secondLabel.font = [UIFont systemFontOfSize:15];
    secondLabel.textColor = [UIColor colorWithHexString:@"666666"];
    [secondLabel sizeToFit];
    
    self.secondTextField = [[UITextField alloc] init];
    _secondTextField.top = _firstTextField.bottom;
    _secondTextField.left = 15;
    _secondTextField.size = CGSizeMake(kBDScreenWidth, 55);
    _secondTextField.textColor = [UIColor colorWithHexString:@"333333"];
    _secondTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:ASLocalizedString(@"请输入支付宝账号")attributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"cdcdcd"],NSFontAttributeName:[UIFont systemFontOfSize:15]}];
    _secondTextField.leftViewMode = UITextFieldViewModeAlways;
    _secondTextField.leftView = secondLabel;
    _secondTextField.delegate = self;
    [backView addSubview:_secondTextField];
    
    UIView *secondBackView = [[UIView alloc] init];
    secondBackView.top = backView.bottom + 10;
    secondBackView.left = 0;
    secondBackView.size = CGSizeMake(kBDScreenWidth, 55);
    secondBackView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:secondBackView];
    
    UILabel *thirdLabel = [[UILabel alloc] init];
    thirdLabel.left = 0;
    thirdLabel.top = 0;
    thirdLabel.text = ASLocalizedString(@"   提现金额：");
    thirdLabel.font = [UIFont systemFontOfSize:15];
    thirdLabel.textColor = [UIColor colorWithHexString:@"666666"];
    [thirdLabel sizeToFit];
    
    self.thirdTextField = [[UITextField alloc] init];
    _thirdTextField.top = 0;
    _thirdTextField.left = 15;
    _thirdTextField.size = CGSizeMake(kBDScreenWidth, 55);
    _thirdTextField.textColor = [UIColor colorWithHexString:@"333333"];
    _thirdTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:ASLocalizedString(@"请输入提现金额（元）")attributes:@{NSForegroundColorAttributeName:[UIColor colorWithHexString:@"cdcdcd"],NSFontAttributeName:[UIFont systemFontOfSize:15]}];
    _thirdTextField.leftViewMode = UITextFieldViewModeAlways;
    _thirdTextField.leftView = thirdLabel;
    _thirdTextField.delegate = self;
    [self createKeyBorad];
    [secondBackView addSubview:_thirdTextField];
    
   
    UILabel *depositLabel = [[UILabel alloc] init];
    if (self.dict) {
        depositLabel.text = [NSString stringWithFormat:ASLocalizedString(@"本次可提现%.2f元，手续费收取%.f%%"),[self.dict[@"total_balance"] floatValue], [[BDUserModel getCurrentUser].mlm_ratio floatValue] * 100];
    }else{
    depositLabel.text = [NSString stringWithFormat:ASLocalizedString(@"本次可提现%.2f元，手续费收取%.f%%"),[BDUserModel getCurrentUser].balance, [[BDUserModel getCurrentUser].ratio floatValue] * 100];
    }
    depositLabel.top = secondBackView.bottom + 10;
    depositLabel.left = 15;
    depositLabel.font = [UIFont systemFontOfSize:11];
    depositLabel.textColor = KBDColorBlue;
    [depositLabel sizeToFit];
    [self.view addSubview:depositLabel];
    
    
    self.sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _sureButton.left = 0;
    _sureButton.size = CGSizeMake(kBDScreenWidth, 45);
    _sureButton.bottom = kBDScreenHeight;
    _sureButton.userInteractionEnabled = NO;
    _sureButton.backgroundColor = [UIColor colorWithHexString:@"999999"];
    [_sureButton setTitle:ASLocalizedString(@"确认提现")forState:UIControlStateNormal];
    [_sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _sureButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:_sureButton];
    
    [[_sureButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self.view endEditing:YES];
        DNPayAlertView *payAlert = [[DNPayAlertView alloc]init];
        payAlert.titleStr = ASLocalizedString(@"请输入支付密码");
        payAlert.detail = ASLocalizedString(@"提现");
        payAlert.amount = [self.thirdTextField.text floatValue];
        [payAlert show];
        payAlert.completeHandle = ^(NSString *inputPwd) {
            [self.paraDic setObject:inputPwd forKey:@"password"];
            [self.paraDic setObject:self.thirdTextField.text forKey:@"apply_amount"];
            [self.paraDic setObject:self.type forKey:@"type"];
            [self.paraDic setObject:self.secondTextField.text forKey:@"acc"];
            [self.paraDic setObject:self.firstTextField.text forKey:@"acc_name"];
            [self balanceWithPata:self.paraDic];
        };
        
        payAlert.returnButtonAction = ^(){
            BDForgetPasswordViewController *forgetVC = [[BDForgetPasswordViewController alloc] init];
            forgetVC.type = ASLocalizedString(@"支付密码");
            [self.navigationController pushViewController:forgetVC animated:YES];
        };
    }];
    
}
-(void)balanceWithPata:(NSDictionary *)para{
    NSString *url = [NSString stringWithFormat:@"%@userWithdrawApplies", KBDBaseURL];
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
    
    [signal subscribeNext:^(id  _Nullable x) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                        message:ASLocalizedString(@"提现申请已经提交，1-3个工作日提现金额会到账")delegate:self
                                              cancelButtonTitle:ASLocalizedString(@"取消")otherButtonTitles:ASLocalizedString(@"确定"),nil];
        [alert show];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        errorCode = error.code;
        switch (error.code) {
            case 40001:{
//                [MBManager hideAlert];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                                message:ASLocalizedString(@"提现的金额比最低提现限额还要低，请填写正确提现金额!")delegate:self
                                                      cancelButtonTitle:ASLocalizedString(@"取消")otherButtonTitles:ASLocalizedString(@"确定"),nil];
                [alert show];
            }break;
            case 40004:{
//                [MBManager hideAlert];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ASLocalizedString(@"注意")message:ASLocalizedString(@"您的余额不足，请填写正确提现金额!")delegate:self
                                                      cancelButtonTitle:ASLocalizedString(@"取消")otherButtonTitles:ASLocalizedString(@"确定"),nil];
                [alert show];
            }break;
            case 40101:{
//                [MBManager hideAlert];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ASLocalizedString(@"注意")message:ASLocalizedString(@"用户等级不够，您必须达到等级2或者VIP2才能提现")delegate:self
                                                      cancelButtonTitle:ASLocalizedString(@"取消")otherButtonTitles:ASLocalizedString(@"确定"),nil];
                [alert show];
            }break;
            case 40105:{
//                [MBManager hideAlert];
                [self firstInterface];
            }break;
            case 40107:{
//                [MBManager hideAlert];
                [self firstInterface];
            }break;
            case 40106:{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ASLocalizedString(@"注意")message:ASLocalizedString(@"未设置支付密码，请前往个人设置页面设置支付密码")delegate:self
                                                      cancelButtonTitle:ASLocalizedString(@"取消")otherButtonTitles:ASLocalizedString(@"确定"),nil];
                [alert show];
            }break;
            default:
                break;
        }
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
}

-(void)firstInterface{
    errorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, kBDScreenHeight)];
    errorView.backgroundColor = [UIColor colorWithRed:0 / 255.0 green:0 / 255.0 blue:0 / 255.0 alpha:0.5];
    [[[[UIApplication sharedApplication] delegate] window] addSubview:errorView];
    
    UIView *errorBackView = [[UIView alloc] init];
    errorBackView.left = 40;
    errorBackView.size = CGSizeMake(kBDScreenWidth - 80, 150);
    errorBackView.top = (kBDScreenHeight - 150) / 2;
    errorBackView.backgroundColor = [UIColor whiteColor];
    [errorView addSubview:errorBackView];
    
    UILabel *reminderLabel = [[UILabel alloc] init];
    reminderLabel.left = 25;
    reminderLabel.top = 50;
    reminderLabel.width = errorBackView.width - 50;
    if (errorCode == 40105) {
        reminderLabel.text = ASLocalizedString(@"支付密码错误，请重试");
    }else if (errorCode == 40107){
        reminderLabel.text = ASLocalizedString(@"你输入的密码已经错误3次了，请重置密码");
    }
    reminderLabel.numberOfLines = 0;
    reminderLabel.textColor = [UIColor colorWithHexString:@"333333"];
    reminderLabel.font = [UIFont systemFontOfSize:15];
    reminderLabel.height = [reminderLabel.text heightForFont:[UIFont systemFontOfSize:15] width:reminderLabel.width];
    [errorBackView addSubview:reminderLabel];
    
    UIButton *forgetPassButton = [UIButton buttonWithType:UIButtonTypeCustom];
    if (errorCode == 40105) {
        [forgetPassButton setTitle:ASLocalizedString(@"忘记密码")forState:UIControlStateNormal];
    }else if (errorCode == 40107){
        [forgetPassButton setTitle:ASLocalizedString(@"重置密码")forState:UIControlStateNormal];
    }
    forgetPassButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [forgetPassButton setTitleColor:[UIColor colorWithHexString:@"48a2d6"] forState:UIControlStateNormal];
    [forgetPassButton sizeToFit];
    forgetPassButton.bottom = errorBackView.height - 25;
    forgetPassButton.right = errorBackView.width - 25;
    [errorBackView addSubview:forgetPassButton];
    [[forgetPassButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        errorView.hidden = YES;
        BDForgetPasswordViewController *forgetVC = [[BDForgetPasswordViewController alloc] init];
        forgetVC.type = ASLocalizedString(@"支付密码");
        [self.navigationController pushViewController:forgetVC animated:YES];
    }];
    
    UIButton *tryButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tryButton setTitle:ASLocalizedString(@"重试")forState:UIControlStateNormal];
    tryButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [tryButton setTitleColor:[UIColor colorWithHexString:@"999999"] forState:UIControlStateNormal];
    [tryButton sizeToFit];
    tryButton.right = forgetPassButton.left - 25;
    tryButton.bottom = forgetPassButton.bottom;
    [errorBackView addSubview:tryButton];
    if (errorCode == 40105) {
        tryButton.hidden = NO;
    }else if (errorCode == 40107){
        tryButton.hidden = YES;
    }
    [[tryButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        errorView.hidden = YES;
//        [self transferAction];
    }];

}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [errorView removeFromSuperview];
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    [self BOOLType:textField Range:range];
    
    return YES;
}

-(void)BOOLType:(UITextField *)textField Range:(NSRange )range{
    BOOL ss1 = [self hasText:self.firstTextField range:range isFirstRegist:textField == self.firstTextField];
    
    BOOL ss2 = [self hasText:self.secondTextField range:range isFirstRegist:textField == self.secondTextField];
    
    BOOL ss3 = [self hasText:self.thirdTextField range:range isFirstRegist:textField == self.thirdTextField];
    
    if (ss1 && ss2 && ss3) {
        self.sureButton.userInteractionEnabled = YES;
        self.sureButton.backgroundColor = [UIColor colorWithHexString:@"ff992b"];
    }else{
        self.sureButton.userInteractionEnabled = NO;
        self.sureButton.backgroundColor = [UIColor colorWithHexString:@"999999"];
    }
}

- (BOOL)hasText:(UITextField *)textField range:(NSRange)range isFirstRegist:(BOOL)isFirstRegist{
    if (isFirstRegist) {
        if (range.length != 0) { // 执行删除方法
            if (textField.text.length <= 1) {
                return NO;
            }
        }
        return YES;
    }else{
        return textField.text.length > 0;
    }
    
}

-(void)createKeyBorad{
    CGFloat width = kBDScreenWidth / 4;
    CGFloat height = 277 / 375.0 * kBDScreenWidth / 4;
    UIView *keyboardView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, height * 4)];
    
    NSArray *btnArr = @[@{@"type":@"label", @"content":@"1"},@{@"type":@"label", @"content":@"2"},@{@"type":@"label", @"content":@"3"},@{@"type":@"image", @"content":@"keyboard_del"},
                        @{@"type":@"label", @"content":@"4"},@{@"type":@"label", @"content":@"5"},@{@"type":@"label", @"content":@"6"},@{@"type":@"label", @"content":ASLocalizedString(@"确认\n支付")},
                        @{@"type":@"label", @"content":@"7"},@{@"type":@"label", @"content":@"8"},@{@"type":@"label", @"content":@"9"},
                        @{@"type":@"image", @"content":@"keyboard_down"},@{@"type":@"label", @"content":@"0"},@{@"type":@"image", @"content":@"keyboard_dot"}];
    
    int index = 0;
    
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            if (i >= 2 && j == 3) {
                continue;
            }
            NSDictionary *dic = btnArr[index];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            if ([[dic objectForKey:@"type"] isEqualToString:@"label"]) {
                [button setTitle:dic[@"content"] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:27];
                button.titleLabel.numberOfLines = 0;
            }else{
                [button setBackgroundImage:[UIImage imageNamed:dic[@"content"]] forState:UIControlStateNormal];
            }
            button.frame = CGRectMake(width * j, height * i, width, height);
            button.backgroundColor = [UIColor whiteColor];
            if (i == 1 && j == 3) {
                button.frame = CGRectMake(width * j, height * i, width, height * 3);
                button.backgroundColor = KBDColorBlue;
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if (index == 3) {
                    //删除
                    [self textFieldChangeString:nil isDeleted:YES];
                }else if (index == 7) {
                    //确认支付
                    NSDecimalNumber *price = nil;
                    if (_thirdTextField.text.length <= 2) {
                        price = [NSDecimalNumber decimalNumberWithString:@"0"];
                    }else {
                        NSString *subString = [_thirdTextField.text substringFromIndex:2];
                        price = [NSDecimalNumber decimalNumberWithString:subString];
                    }
                    NSComparisonResult result_clearrate_float = [price compare:[NSDecimalNumber decimalNumberWithString:@"0"]];
                    if (result_clearrate_float == 1) {
                        [MBManager showBriefAlert:ASLocalizedString(@"请输入正确的金额")clickHidden:YES clickBlock:nil];
                        return ;
                    }
                    [_sureButton sendActionsForControlEvents:UIControlEventTouchUpInside];
                }else if (index == 11) {
                    //回收键盘
                    [_thirdTextField resignFirstResponder];
                }else if (index == 13) {
                    //dot
                    [self textFieldChangeString:@"." isDeleted:NO];
                }else {
                    [self textFieldChangeString:dic[@"content"] isDeleted:NO];
                }
            }];
            
            //            button.endWindowEditingWhenTouch = NO;
            [keyboardView addSubview:button];
            index++;
        }
    }
    
    for (int i = 0; i < 5; i++) {
        UIView *line_v = [[UIView alloc] init];
        line_v.size = CGSizeMake(1, height * 4);
        line_v.centerX = width * i;
        line_v.backgroundColor = [UIColor colorWithHexString:@"#e5e5e5"];
        [keyboardView addSubview:line_v];
        
        UIView *line_h = [[UIView alloc] init];
        if (i == 2 || i == 3) {
            line_h.size = CGSizeMake(width * 3, 1);
        }else{
            line_h.size = CGSizeMake(width * 4, 1);
        }
        
        line_h.centerY = height * i;
        line_h.backgroundColor = [UIColor colorWithHexString:@"#e5e5e5"];
        [keyboardView addSubview:line_h];
        
        line_v.userInteractionEnabled = NO;
        line_h.userInteractionEnabled = NO;
    }
    _thirdTextField.inputView = keyboardView;
    [_thirdTextField reloadInputViews];
    
    
}

- (void)textFieldChangeString:(NSString *)string isDeleted:(BOOL)isDeleted{
    NSString *curentText = _thirdTextField.text;
    NSRange ranger = NSMakeRange(0, 1);
    if (isDeleted) {
        [_thirdTextField deleteBackward];
        ranger.length = 1;
    }else {
        if ([string containsString:@"."]) {
            //如果当前包含小数点，那么不处理
            if (![curentText containsString:@"."]) {
                //判断小数点前面没有整数部分，那么要拼接一个0
                if (curentText.length <= 0) {
                    _thirdTextField.text = [curentText stringByAppendingString:@"0."];
                }else{
                    [_thirdTextField insertText:@"."];
                }
            }
        }else {
            //当输入数字的时候，整数部分不超过5位，小数部分不超过2位
            if ([curentText containsString:@"."]) {
                NSRange dotRange = [curentText rangeOfString:@"."];
                if (dotRange.location + dotRange.length + 2 > curentText.length) {
                    [_thirdTextField insertText:string];
                }
            }else{
                if (curentText.length < 7) {
                    [_thirdTextField insertText:string];
                }
            }
        }
        ranger.length = 0;
    }
    [self BOOLType:_thirdTextField Range:ranger];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
